<template>
    <div>
        <!-- 面包屑导航区域 -->
       <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
       </el-breadcrumb>
       <!-- 卡片视图区域 -->
       <el-card class="box-card">
           <!-- 搜索与添加区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                  <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserLIst">
                    <el-button slot="append" icon="el-icon-search" @click="getUserLIst" >
                    </el-button>
                  </el-input>
               </el-col>
               <el-col :span="6"><el-button type="primary" @click="addDialogVisible=true">添加用户</el-button></el-col>
            </el-row>
            <!-- 用户列表区域 -->
             <el-table :data="userList" stripe border >
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="username" label="姓名" width="80px" ></el-table-column>
                <el-table-column prop="email" label="邮箱"  ></el-table-column>
                <el-table-column prop="mobile" label="电话"  ></el-table-column>
                <el-table-column prop="role_name" label="角色"  ></el-table-column>
                <el-table-column label="状态" width="80px"> 
                    <template slot-scope="scope" >
                       <el-switch v-model="scope.row.mg_state" @change="userStatusChange(scope.row)" ></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200px">
                     <template slot-scope="scope">
                       <!-- 修改按钮 -->
                       <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">
                       </el-button>
                       <!-- 删除按钮 -->
                       <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)">
                       </el-button>
                       <!-- 定义角色按钮 -->
                        <el-tooltip effect="dark" content="定义角色" placement="top" :enterable="false">
                          <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoles(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 4, 5]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户框区域 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addFormClose">
            <!-- 添加用户主体区域 -->
            <el-form ref="addForm_ref" :model="addForm" :rules="addForm_rules" label-width="80px">
                <!-- 用户名 -->
                <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username" ></el-input>
                </el-form-item>
                <!-- 密码区域 -->
                <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email" ></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 添加用户底部区域 -->
            <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
         </span>
        </el-dialog>

        <!-- 修改用户的对话框 -->
        <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editUserClose">
            <el-form ref="editUser_ref" :model="editUser" :rules="editUser_rules" label-width="80px">
                <el-form-item label="用户名称">
                    <el-input v-model="editUser.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editUser.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editUser.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 定义角色的对话框 -->
        <el-dialog
        title="定义角色"
        :visible.sync="setRoledialogVisible"
        width="50%" @close="setRoledialogClose">
            <div>
                <p>当前的用户：{{roleInfo.username}}</p>
                <p>当前的角色：{{roleInfo.role_name}}</p>
                <p>分配新角色：
                    <el-select v-model="selectedRole" placeholder="请选择">
                        <el-option
                        v-for="item in rolesList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoledialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRolesConfirm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data (){
        // 邮箱验证规则
        const checkEmail = (rule,value,callback) => {
            const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
            if (regEmail.test(value)) {
                return callback();
            };
            callback(new Error('请输入合法的邮箱'));
        }
         // 手机号码验证规则
        const checkMobile = (rule,value,callback) => {
            const regMobile = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/;
            if (regMobile.test(value)) {
                return callback();
            };
            callback(new Error('请输入合法的手机号'));
        }
        return { 
            queryInfo:{
                query:'',
                pagenum:1,
                pagesize:2
            },
            userList:[],
            total:0,
            // 添加用户对话框的显示与隐藏
            addDialogVisible:false,
            //添加用户data
            addForm:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            // 添加用户的表单验证规则
            addForm_rules:{
                username:[  
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入登录密码', trigger: 'blur' },
                    { min: 6, max: 10, message: '长度在 6到 10 个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                     { validator: checkEmail, trigger: 'blur' }
                ],
                mobile:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                     { validator: checkMobile, trigger: 'blur' }
                ]
            },
            // 控制修改用户的对话框显示与隐藏
            editDialogVisible:false,
            editUser:{},
            // 修改用户的验证规则
            editUser_rules:{
                 email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                     { validator: checkEmail, trigger: 'blur' }
                ],
                mobile:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                     { validator: checkMobile, trigger: 'blur' }
                ]
            },
            // 控制定义角色对话框的显示与隐藏
            setRoledialogVisible:false,
            roleInfo:{},
            rolesList:[],
            selectedRole:''
        }
    },
    created(){
        this.getUserLIst();
    },
    methods:{
        // 获取用户列表
        async getUserLIst(){
            const {data:res} = await this.$http.get('users',{params:this.queryInfo});
            if (res.meta.status !== 200) return this.$message.error('获取用户列表失败');
            console.log(res);
            this.total = res.data.total;
            this.userList = res.data.users;
        },
        handleSizeChange(newsiaze){
            this.queryInfo.pagesize = newsiaze;
            this.getUserLIst();
        },
        handleCurrentChange(newpage){
            this.queryInfo.pagenum = newpage;
            this.getUserLIst();
        },
        // 更新用户状态
       async userStatusChange(userInfo){
          const res = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
        //   console.log(res);
          if(res.status !== 200) {return this.$message.error('状态更新失败');
          userInfo.mg_state = !userInfo.mg_state};
          this.$message.success('状态更新成功');

        },
        // 关闭添加用户重置表单
        addFormClose(){
            this.$refs.addForm_ref.resetFields();
        },
        // 点击确定按钮添加用户
        addUser(){
            this.$refs.addForm_ref.validate(async valid => {
                if(!valid) return;
                const {data:res} =await this.$http.post('users',this.addForm);
                // console.log(res);
                if(res.meta.status != 201) {return this.$message.error('添加用户失败')}
                this.$message.success('添加用户成功');
                this.addDialogVisible = false;
                this.getUserLIst();
            })
        },
        // 点击按钮修改用户信息
        async showEditDialog(id){
            // console.log(id);
            const {data:res} = await this.$http.get('users/'+id);
            if(res.meta.status != 200) {return this.$message.error('查询用户信息失败')}
            this.editUser = res.data;
            this.editDialogVisible = true;
        },
        // 重置修改用户的对话框
        editUserClose(){
            this.$refs.editUser_ref.resetFields();
        },
        // 修改用户
        editUserInfo(){
          this.$refs.editUser_ref.validate(async valid =>{
              if(!valid){return};
              const {data:res} = await this.$http.put('users/' + this.editUser.id,
              {email:this.editUser.email,mobile:this.editUser.mobile});
            //   console.log(res);
            if(res.meta.status != 200) {return this.$message.error('更新用户失败')}
            this.editDialogVisible = false;
            this.getUserLIst();
            this.$message.success('更新用户成功')
          })  
        },
        // 删除用户
        async removeUserById(id){
            // console.log(id);
            const confirmRes =await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error => error);
            if (confirmRes !== 'confirm'){return this.$message.info('已取消删除用户')};
            const {data:res} =await this.$http.delete('users/'+id)
            if(res.meta.status != 200) {return this.$message.error('删除用户失败')};
            this.getUserLIst();
            this.$message.success('删除用户成功')
        },

        // 定义角色
        async setRoles(roleInfo){
            this.roleInfo = roleInfo;
            const {data:res} = await this.$http.get('roles');
            if(res.meta.status != 200) {return this.$message.error('获取角色失败')};
            this.rolesList = res.data;
            this.setRoledialogVisible = true;
        },

        // 设置角色
        async setRolesConfirm (){
            if(!this.selectedRole){
                return this.$message.error('请选择要分配的角色')
            }
            const {data:res} =await this.$http.put(`users/${this.roleInfo.id}/role`,{rid:this.selectedRole});
            if(res.meta.status != 200) {return this.$message.error('设置角色失败')};
            this.$message.success('设置角色成功');
            this.getUserLIst();
            this.setRoledialogVisible = false;
        },
        setRoledialogClose(){
            this.rolesList = [];
            this.selectedRole = '';
        }
    }
}
</script>

<style lang="less" scoped>
.el-form{
    font-size: 12px;
}
</style>